<?php
namespace app\index\controller;
use app\index\controller\BaseController;
use think\Db;

class GoodsController extends BaseController {

	//商品详情
	public function goods_show() {
		$goods_info = db('goods')
						->field('id,goods_name,thumb,cost_price,sale_price,store,sales,content')
						->where('id',input('goods_id'))
						->find();
		
		$this->assign('goods_info',$goods_info);
		
		return $this->fetch();
	}
	
	
	//商品列表
	function goods_list(){
		if($_POST){
			if(input("page")){
				$page=input("page");
			}
			if(input("name")){
				$w['goods_name'] = ['like', '%'.input("name").'%'];
			}			
			$w['is_on_sale'] = 1;
			$goods_info = db('goods')
								->field('id,goods_sn,goods_name,store,sale_price,thumb')
								->where($w)
								->order("sort desc")
								->page($page,20)
								->select();
			return json(['list'=>$goods_info]);
		}
		return $this->fetch();
	}
	
	//购买商品
	function goods_buy(){
		//获取商品信息
		$goods_info = db('goods')->where('id',input('goods_id'))->find();
		if(request()->isPost()) {
			
			$result = true;
			Db::startTrans();
			
			
			$order_sn = order_create_no();
			//生成订单
			$rest1 = add_order($goods_info,$order_sn,1);
			if(!$rest1) $result= false;
			
			//生成订单详情
			
			
			
			
			
			if($result){
				Db::commit();
				return json(['code'=>200,'msg'=>'购买成功','url'=>url('member/index')] );
			}else{
				Db::rollback();
				return json(['code'=>403,'msg'=>'购买失败']);
			}
			
			
		}
		
		
		$this->assign('goods_info',$goods_info);
		return $this->fetch();
	}

	//添加购物车
	function add_car(){
		
	}
	
	


















	public function index() {
		//获取商品信息
		$goods_list = db('goods')
						->order('add_time desc')
						->limit(10)
						->select();
		
		$this->assign('goods_list',$goods_list);
		return $this->fetch();
	}
	
	function js_index(){
		$latitude = input('latitude');
		$longitude = input('longitude');
		$page=input('page');
		
		$goods_list = db('goods')
						->field('goods_id,goods_name,logo,cate_id,cate2_id,cost_price,sale_price')
						->limit(15)
						->page($page)
						->select();
		if($goods_list){
			return json(['code'=>200,'data'=>$goods_list]);
		}else{
			return json(['code'=>403,'msg'=>'暂无数据']);
		}
		
	}
	
	
	public function lists() {
		$goodstype = input('goodstype');
		//商品分类
		$goodstype_list = db('goodstype')->where('pid',0)->select();
		
		$goodstype_name="";
		if(input('goodstype')) {
			$where['a.cate_id'] = $goodstype;
			
			foreach($goodstype_list as $key=>$value){
				if($value['id'] == $goodstype)$goodstype_name = $value['name'];
			}
			
		}
		
		$where['a.is_on_sale'] = 1;
		
		$time_sort = 'a.add_time desc';
		if(input('time_sort')){
			if(input('time_sort') == 2){
				$time_sort = 'a.add_time asc';
			}
		}  
		
		$price_sort = "a.cost_price asc";
		if(input('price_sort')){
			if(input('price_sort') == 2){
				$time_sort = 'a.cost_price asc';
			}
		}
		
		
		$order_type = $time_sort.",".$price_sort;
		//商品列表
		$goods_list = db('goods')
						->alias('a')
						->field('a.goods_id,a.goods_name,a.logo,a.cate_id,a.cate2_id,a.cost_price,a.sale_price,a.add_time,b.name')
						->join('goodstype b ','a.cate_id = b.id','left')
						->where($where)
						->order($order_type)
						->limit(15)
						->select();
		
		$this->assign('goodstype_list',$goodstype_list);
		$this->assign('goods_list',$goods_list);
		$this->assign('goodstype',$goodstype);
		$this->assign('goodstype_name',$goodstype_name);
		$this->assign('time_sort',input('time_sort'));
		$this->assign('price_sort',input('price_sort'));
		return $this->fetch();
	}
	
	function js_lists(){
		$goodstype = input('goodstype');
		$page=input('page');
		
		$goods_list = db('goods')
						->field('goods_id,goods_name,logo,cate_id,cate2_id,cost_price,sale_price')
						->where('is_on_sale',1)
						->where('cate_id',$goodstype)
						->limit(1)
						->page($page)
						->select();
		if($agent_list){
			return json(['code'=>200,'data'=>$goods_list]);
		}else{
			return json(['code'=>403,'msg'=>'暂无数据']);
		}
	}
	function add_collect(){
		//查找当前用户收藏状态
		$collect_info = db('collect')
							->where('collect_type',2)
							->where('collect_id',input('goods_id'))
							->where('user_id',session('user_id'))
							->find();
		if($collect_info){
			$resutl = db('collect')->where('id', $collect_info['id'])->update(['user_id' => 0]);
			if($resutl){
				return json(['code'=>200,'msg'=>'取消收藏成功']);
			}else{
				return json(['code'=>403,'msg'=>'取消收藏失败']);
			}
		}else{
			$data = ['collect_type' => 2, 'collect_id' =>input('goods_id'),'user_id'=>session('user_id')];
			
			$resutl = db('collect')
						//->data(['user_id'=>session('user_id'),'collect_id'=>input('goods_id'),'collect_type'=>2])
						->insert($data);
			if($resutl){
				return json(['code'=>200,'msg'=>'收藏成功']);
			}else{
				return json(['code'=>403,'msg'=>'收藏失败']);
			}
		}
	}
	
	
	public function shop() {
		$agent_info = db('agent')
						->where('id',input('agent_id'))
						->find();
						
		$goods_list = db('goods')
						->field('goods_id,agent_id,goods_name,logo,cost_price,sale_price,sales')
						->order('add_time desc')
						->limit(3)
						->where('agent_id',$agent_info['id'])
						->select();
		$this->assign('goods_list',$goods_list);		
		$this->assign('agent_info',$agent_info);
		return $this->fetch();
	}
	public function shoplist() {
		
		if(request()->isAjax()){
			$latitude = input('latitude');
			$longitude = input('longitude');
			
			if(input('agent_type'))$where['agent_property'] =input('agent_type');
			
			//附近商家
			$juli = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-longitude*PI()/180)/2),2)))*1000)';
			
			$order_sort = 'asc';
			if(input('juli') == 2){
				$order_sort = 'desc';
			}
			
			if(strlen(input('town_name'))>1)$where['town_name'] = input('town_name');
			
			if(input('agent_type')>0)$where['agent_property'] = input('agent_type');
			
			$where['id'] = ['>',0];
			$agent_list = db('agent')
							->field('id,agent_name,address,mobile,longitude,latitude,province_name,city_name,town_name,country_name,logo,'.$juli."as juli ")
							->order("juli ".$order_sort)
							->page(input("page"),10)
							->where($where)
							->select();
			if($agent_list){
				return json(['code'=>200,'data'=>$agent_list]);
			}else{
				return json(['code'=>403,'msg'=>'暂无数据']);
			}
		}

		return $this->fetch();
	}
	
	
	function pay_order(){
		$post_data = input('post_data');
		
		$order_str = $order_arr = explode("|", substr($post_data,0,strlen($post_data)-1));
		
		//组装订单信息
		$order_infos = array();
		foreach($order_str as $key=>$value){
			$order_info['order_id'] = explode(":", $value)[0];
		
			$str_info = explode(",", explode(":", $value)[1]);
			
			foreach($str_info as $k=>$v){
				
				$order_info['express_type'] = $str_info[0];
				
				$order_info['memo'] = $str_info[1];
			}
			$order_infos[]=$order_info;
		}
		
		//获取用户地址信息
		$user_address = db('member_address')
						->where('user_id',session('user_id'))
						->where('is_default',1)
						->find();
						
						
		$result = true;
		Db::startTrans();
		//跟新订单信息
		foreach($order_infos as $key=>$vale){
			$rest = update_order($vale['order_id'],$vale['express_type'],$user_address['id'],$vale['memo']);
			if(!$rest) $result = false;
		}
		
		//计算订单金额
		$total_price = 0;
		foreach($order_infos as $key=>$vale){
			$money = db('good_order')->where('id',$vale['order_id'])->value("total_price");
			$total_price = bcadd($money, $total_price, 2);
			
		}
		
		//获取用户信息
		$user_info = db('member')->where('user_id',session('user_id'))->find();
		//检查用户余额
		if(bccomp($user_info['score'], $total_price, 2)<0){
			return json(['code'=>403,'msg'=>'账户余额不足']);
		}
		
		//生成支付日志
		foreach($order_infos as $key=>$vale){
			$order_info = db('good_order')->where('id',$vale['order_id'])->find();
			
			$order_sn =  order_create_no();
			
			//减去用户余额
			$rest1 = db('member')->where('user_id', session('user_id'))->setDec('score',$order_info['total_price']);
			if(!$rest1) $result = false;
			//用户消费余额变化日志
			$rest2 = add_member_consume($user_info['user_id'],$order_info['total_price'],$order_sn,3,'商城消费'.$order_info['total_price']);
			if(!$rest2) $result = false;
			
			//新增支付日志
			$rest3 = add_pay_log(session('user_id'),$order_info['agent_id'],$order_info['total_price'],2,$order_sn,
			5,1,"购买商品",$order_info['id'],now_time());
			if(!$rest3) $result = false;
			
			//支付回调
			$rest4 = pay_callback($order_sn);
			if(!$rest4)$result = false;
		}
		
		if($result){
			Db::commit();
			return json(['code'=>200,'msg'=>'购买成功','url'=>url('member/index')] );
		}else{
			Db::rollback();
			return json(['code'=>403,'msg'=>'购买失败']);
		}
		
	}

	function add_cart(){
		
		//获取商品信息
		$goods_info = db('goods')->where('goods_id',input('goods_id'))->find();
		
		//获取商家信息
		$agent_info = db('agent')->where('id',$goods_info['agent_id'])->find();
		
		$in_cart = db('good_cart')->where('goods_id',input('goods_id'))->where('user_id',session('user_id'))->find();
		if($in_cart){
			return json(['code'=>200,'msg'=>'添加成功']);
		}else{
			if($goods_info){
				$data['user_id'] 	=  session('user_id');
				$data['goods_id'] 	= $goods_info['goods_id'];
				$data['agent_id'] 	= $goods_info['agent_id'];
				$data['goods_name'] = $goods_info['goods_name'];
				$data['agent_name'] = $agent_info['agent_name'];
				$data['cost_price'] = $goods_info['cost_price'];
				$data['sale_price'] = $goods_info['sale_price'];
				$data['logo'] 		= $goods_info['logo'];
				$data['add_time'] 	= now_time();
				
				$result = db('good_cart')->insert($data);
				
				if($result){
					return json(['code'=>200,'msg'=>'添加成功']);
				}else{
					return json(['code'=>405,'msg'=>'添加失败']);
				}
				
			}else{
				return json(['code'=>403,'msg'=>'数据异常，商品不存在']);
			}
		}
	}


	function shopcart(){
		//获取购物列表
		$cart_list = db('good_cart')
						->where('user_id',session('user_id'))
						->select();
		
		$agent_goods = array();
		$goods_ids='';
		foreach($cart_list as $key=>$value){
			$goods_ids=$goods_ids.$value['goods_id'].',';
			$agent_goods[$value['agent_id']][] = $value;
		}
		$this->assign('agent_goods',$agent_goods);	
		
		//计算金额
		$total_money = db('goods')
						->where('goods_id','in',substr($goods_ids,0,strlen("$goods_ids")-1))
						->sum('cost_price');
		
		$this->assign('total_money',$total_money);	
		
		return $this->fetch();
	}
	
	function add_cart_order(){
		$data = input('post.');
		
		$goods_arr = explode(",", $data['post_data']);
		$goods_list = array();
		foreach($goods_arr as $key=>$value){
			
			$goods_id = explode(":", $value);
			
			//获取商品信息
			$goods_info = db('goods')->where('goods_id',$goods_id[0])->find();
			
			$goods_info['goods_num'] = $goods_id[1];
			
			$goods_list[$goods_info['agent_id']][]=$goods_info;
		}
		
		$result = true;
		Db::startTrans();
		$order_ids = "";
		foreach($goods_list as $key=>$value){
		
			$order_sn = order_create_no();
			/*================生成订单start=====================*/
			//新增订单
			$rest1  = add_order($value,$order_sn);
			if(!$rest1) $result = false;
			
			$order_id = db('good_order')->getLastInsID();
			$order_ids .= $order_id.",";
			//订单详情
			$rest2 = add_order_item($value,$order_id);
			if(!$rest2) $result = false;
			/*================生成订单end=====================*/
		}
		$goods_ids = "";
		foreach($goods_arr as $key=>$value){
			
			$goods_id = explode(":", $value);
			$goods_ids .= $goods_id[0].",";
			
		}
		
		//删除购物车
		$rest3 = db('good_cart')
				->where('user_id',session('user_id'))
				->where('goods_id','in',substr($goods_ids,0,strlen($goods_ids)-1))
				->delete();
		if(!$rest3) $result = false;
		
		$order_ids = substr($order_ids,0,strlen($order_ids)-1);
		
		if($result){
			Db::commit();
			return json(['code'=>200,'msg'=>'添加订单成功','data'=>$order_ids] );
		}else{
			Db::rollback();
			return json(['code'=>403,'msg'=>'添加订单失败']);
		}
	}
	
	function del_cart_order(){
		$cart_id = input('cart_id');
		
		$result = db('good_cart')->where('id',$cart_id)->delete();
		if($result){
			return json(['code'=>200,'msg'=>'删除成功']);
		}else{
			return json(['code'=>403,'msg'=>'删除失败']);
		}
	}
	
	
	function add_order(){
	
		$data = input('post.');
		//获取商品信息
		$goods_info = db('goods')->where('goods_id',$data['goods_id'])->find(); 		
		//获取用户信息
		$user_info = db('member')->where('user_id',session('user_id'))->find();
		//计算金额
		$total_price = bcmul($data['nums'],$goods_info['cost_price'], 2);
		//检查用户余额
		if(bccomp($user_info['score'], $total_price, 2)<0){
			return json(['code'=>403,'msg'=>'账户余额不足']);
		}
		
		if($goods_info){
			
			if($goods_info['stock'] < $data['nums']){
				return json(['code'=>403,'msg'=>'库存不足']);
			}else{
				$result = true;
				Db::startTrans();
				
				$order_sn =  order_create_no();
				//减去用户余额
				$rest1 = db('member')->where('user_id', session('user_id'))->setDec('score',$total_price);
				if(!$rest1) $result = false;
				
				//用户消费余额变化日志
				$rest2 = add_member_consume($user_info['user_id'],$total_price,$order_sn,$data['order_type']);
				if(!$rest2) $result = false;
				
				//新增订单
				$rest3 = add_order($data['goods_id'],$data['nums'],$data['order_type'],$data['memo'],$data['address_id'],$order_sn);
				if(!$rest3) $result = false;
				
				$order_id = db('good_order')->getLastInsID();
				
				//订单详情
				$rest4 = add_order_item($order_id,$data['goods_id'],$data['nums'],$goods_info['cost_price'],$total_price,$goods_info['goods_name']);
				if(!$rest4) $result = false;
				
				//新增支付日志
				$rest5 = add_pay_log(session('user_id'),$goods_info['agent_id'],$total_price,$data['order_type'],$order_sn,
				5,1,"购买商品",$order_id,now_time());
				if(!$rest5) $result = false;
				
				if($result){
					Db::commit();
					//支付回调
					pay_callback($order_sn);
					return  json(["code"=>200,"msg"=>"购买成功",'url'=>url('member/index')]);
				}else{
					Db::rollback();
					return  json(["code"=>405,"msg"=>"购买成功失败"]);
				}
				
			}
			
		}else{
			return json(['code'=>403,'msg'=>'商品不存在，数据异常']);
		}
		
	}
	
	
	function cancel_order(){
		if(request()->isAjax()){
			$order_info = db('good_order')->where('id',input('order_id'))->where('user_id',session('user_id'))->find();
			if($order_info){
				 $result = db('good_order')->where('id',$order_info['id'])->update(['status'=>8]);
				 if($result){
				 	return json(['code'=>200,'msg'=>'订单已取消']);
				 }else{
				 	return json(['code'=>403,'msg'=>'订单取消失败']);
				 }
			}else{
				return json(['code'=>403,'msg'=>'订单不存在，数据异常']);
			}
		}
	}
	
	
	function take_order(){
		if(request()->isAjax()){
			$order_info = db('good_order')->where('id',input('order_id'))->where('user_id',session('user_id'))->find();
			if($order_info){
				 $result = db('good_order')->where('id',$order_info['id'])->update(['status'=>4]);
				 if($result){
				 	return json(['code'=>200,'msg'=>'确认收货成功']);
				 }else{
				 	return json(['code'=>403,'msg'=>'确认收货失败']);
				 }
			}else{
				return json(['code'=>403,'msg'=>'订单不存在，数据异常']);
			}
		}
	}
	
	function order_comment(){
		
		if(request()->isAjax()){
			$data = input('post.');
			
			$result = true;
			Db::startTrans();
			
			$data['uid'] = session('user_id');
			$data['add_time'] = session('user_id');
			
			$rest1 = db('good_comment')->insert($data);
			if(!$rest1) $result =false;
			
			//更新订单状态
			$rest2 = db('good_order')->where('id',$data['order_id'])->update(['status'=>6]);
			if(!$rest2) $result =false;
			
			if($result){
				Db::commit();
				return json(['code'=>200,'msg'=>'评论成功','url'=>url('member/orders')]);
			}else{
				Db::rollback();
				return json(['code'=>403,'msg'=>'评论失败']);
			}
		}
		
		$order_info = db('good_order')->where('id',input('order_id'))->where('user_id',session('user_id'))->find();
		
		$order_item = db('order_items')->where('order_id',$order_info['id'])->where('goods_id',input('goods_id'))->find();
		$order_info['order_item'] = $order_item;
		$this->assign('order_info',$order_info);
		
		return $this->fetch();
	}
	
	function comment_list(){
		
		//查找商品评价
		$comment_list = db('good_comment')
							->alias('a')
							->field('a.*,b.user_id,b.nick_name,b.logo as member_logo')
							->join('member b','b.user_id = a.uid','LEFT')
							->where('a.goods_id',input('goods_id'))
							->order('add_time desc')
							->page(input('page'))
							->limit(20)
							->select();
		$goods_info = db('goods')
						->alias('a')
						->field('a.goods_id,a.agent_id,a.goods_name,a.logo,a.cost_price,a.sale_price,a.express_type,a.sales,a.content,
						b.agent_name,b.address,b.province_name,b.city_name,b.town_name,b.country_name')
						->join('agent b','b.id = a.agent_id','LEFT')
						->where('goods_id',input('goods_id'))
						->find();
		//查找当前用户收藏状态
		$is_collect = db('collect')
						->where('collect_type',2)
						->where('collect_id',$goods_info['goods_id'])
						->where('user_id',session('user_id'))
						->find();
		
		
		$this->assign('is_collect',$is_collect);
		$this->assign('goods_info',$goods_info);	
		$this->assign('comment_list',$comment_list);				
		return $this->fetch();
	}
}
